<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2017/3/24
 * Time: 21:23
 */

namespace Aoe\Database;


use Aoe\Attributes\Container\Argument;
use Aoe\Database\Platform\Mysql;
use Aoe\Database\Platform\Sqlite;
use Aoe\Util\Exception;
use Aoe\Util\Manager\ClosureCollection;

/**
 * # Pdo连接生成器
 */
class Database
{
    const string ERR_DRIVER = '没有${class}类型数据库驱动';
    const string ERR_CONFIG = '未配置数据库';
    const string PLATFORM   = 'type';

    private static array $preset = [
        'Mysql'  => Mysql::class,
        'Sqlite' => Sqlite::class
    ];

    private ClosureCollection $platforms;
    private SqlBuilder    $builder;
    
    public function __construct(#[Argument('database')] protected array $defs)
    {
        $this->platforms = new ClosureCollection($this->create_driver(...));
        $this->builder   = new SqlBuilder();
    }
    
    /**
     * @param int|string $name
     *
     * @return SqlBuilder
     * @throws \Exception
     */
    public function use(int | string $name): SqlBuilder
    {
        return $this->builder->setPlatform($this->platforms->get($name));
    }
    
    /**
     * @throws \Exception
     */
    protected function create_driver(int | string $name): Platform
    {
        $db = $this->defs[$name] ?? null;
        if (empty($db) || !is_array($db)) throw new Exception(self::ERR_CONFIG);

        $platform = ucfirst($db[self::PLATFORM] ?? 'Mysql');
        $class = self::$preset[$platform] ??  __NAMESPACE__ . '\\Platform\\' . ucfirst($db[self::PLATFORM]);
        if (!class_exists($class)) throw new Exception(self::ERR_DRIVER, ['class' => $class]);
        
        return new $class($db);
    }
}